package graphics.seal;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import graphics.base.BaseUtil;
import graphics.base.Point3D;
import graphics.base.TransformParam;
import graphics.base.Triangle;

public class SealUtils {

	public static Seal initSeal(String stlPath) {
		Seal seal = new Seal();
		Triangle tri = null;
		try {

			FileInputStream stl = new FileInputStream(stlPath);
			stl.skip(84);
			byte block[] = new byte[2000];
			int blen = 0;
			boolean isFirst = true;
			while ((blen = stl.read(block)) != -1) {
				for (int i = 0; i + 50 <= blen; i += 50) {
					tri = new Triangle();
					// 法向量12个字节
					tri.nx = BaseUtil.toFloat(block, i);// 4
					tri.ny = BaseUtil.toFloat(block, i + 4);// 4
					tri.nz = BaseUtil.toFloat(block, i + 4 * 2);// 4

					// 顶点坐标36字节
					tri.x1 = BaseUtil.toFloat(block, i + 4 * 3);// x
					tri.y1 = BaseUtil.toFloat(block, i + 4 * 4);// y
					tri.z1 = BaseUtil.toFloat(block, i + 4 * 5);// z

					tri.x2 = BaseUtil.toFloat(block, i + 4 * 6);// x
					tri.y2 = BaseUtil.toFloat(block, i + 4 * 7);// y
					tri.z2 = BaseUtil.toFloat(block, i + 4 * 8);// z

					tri.x3 = BaseUtil.toFloat(block, i + 4 * 9);// x
					tri.y3 = BaseUtil.toFloat(block, i + 4 * 10);// y
					tri.z3 = BaseUtil.toFloat(block, i + 4 * 11);// z

					if (isFirst) {
						seal.setMax(tri.x1, tri.y1, tri.z1);
						seal.setMin(tri.x1, tri.y1, tri.z1);
						isFirst = false;
					} else {
						seal.updateMax(tri);
						seal.updateMin(tri);
					}
				}

			}
			stl.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return seal;
	}

	/**
	 * imgPoint(manX,manY,maxZ)变换到原印章xyMax点(manX,manY,minZ)
	 * 
	 * @param sealMinPoint
	 * @param image3DMin
	 * @param image3DMax
	 * @return
	 */
	public static TransformParam initTransformParam(Point3D sealMinPoint, Point3D sealMaxPoint, Point3D imgXYMinPoint, Point3D imgXYMaxPoint) {
		TransformParam tfp = new TransformParam();
		float sealWidth = sealMaxPoint.x - sealMinPoint.x;
		float sealLenght = sealMaxPoint.y - sealMinPoint.y;
		float imgXYWidth = imgXYMaxPoint.x - imgXYMinPoint.x;
		float imgXYLenght = imgXYMaxPoint.y - imgXYMinPoint.y;

		tfp.scaleX = tfp.scaleY = tfp.scaleZ = sealWidth < sealLenght ? sealWidth / imgXYWidth : sealLenght / imgXYLenght;

		// 原点在正对公司logo的面时候的左边,所以这样移动
		tfp.moveX = sealMaxPoint.x - imgXYMaxPoint.x * tfp.scaleX;
		tfp.moveY = sealMaxPoint.y - imgXYMaxPoint.y * tfp.scaleX;
		tfp.moveZ = sealMinPoint.z - imgXYMinPoint.z * tfp.scaleX;
		return tfp;
	}

}
